package com.sky.rabc.common;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.Objects;

/**
 * @author 许照
 * @className RedissonCommon
 * @description Redisson 操作工具类
 * @date 2024/5/28
 */
public class RedissonCommon {
    /**
     * redisson客户端
     */
    final RedissonClient redissonClient;

    public RedissonCommon(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 查看键是否存在
     *
     * @param key 键
     * @return true:存在,false:不存在
     */
    public boolean exists(String key) {
        return redissonClient.getBucket(key).isExists();
    }

    /**
     * 设置缓存有效期
     *
     * @param key        键
     * @param expireTime 有效时间(毫秒)
     * @return true:成功,false:失败
     */
    public boolean expire(String key, long expireTime) {
        return redissonClient.getBucket(key).expire(Duration.ofMillis(expireTime));
    }


    /**
     * 字符串set操作
     *
     * @param key        键
     * @param value      值
     * @param expireTime 有效时间(毫秒),设置Null时为永久有效
     * @param <T>        泛型
     */
    public <T> void setValue(String key, T value, Long expireTime) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        bucket.set(value);
        if (Objects.nonNull(expireTime)){
            bucket.expire(Duration.ofMillis(expireTime));
        }
    }

    /**
     * 字符串get操作
     *
     * @param key 键
     * @param <T> 泛型
     * @return 值, 泛型
     */
    public <T> T getValue(String key) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 删除键
     *
     * @param key 键
     * @return true:成功,false:失败
     */
    public boolean delete(String key) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.delete();
    }


}
